package com.wanmait.schedule.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanmait.schedule.entity.CompanyUser;
import com.wanmait.schedule.entity.Userinfo;
import com.wanmait.schedule.service.CompanyUserService;
import com.wanmait.schedule.entity.*;
import com.wanmait.schedule.service.CompanyService;
import com.wanmait.schedule.service.DepartmentService;
import com.wanmait.schedule.service.PositionService;
import com.wanmait.schedule.service.UserinfoService;
import com.wanmait.schedule.util.JWTUtils;
import com.wanmait.schedule.util.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Service;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2022-03-02
 */
@RestController
@RequestMapping("userinfo")
public class UserinfoController {

    @Resource
    private DepartmentService departmentService;
    @Resource
    private PositionService positionService;
    @Resource
    private CompanyService companyService;
    @Resource
    private UserinfoService userinfoService;
    @Resource
    private CompanyUserService companyUserService;

    /*
    * 2022.03.08
    * 王志羽
    * 用户登录
    * */
    @PostMapping("UserLogin")
    public Result login(@RequestBody Userinfo userinfo){
       //System.out.println("userinfo::"+userinfo);
        Userinfo loginUser = userinfoService.login(userinfo);
        //System.out.println("loginUser::"+loginUser);
        if(loginUser != null){
            String token = JWTUtils.createToken(loginUser);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("loginUser",loginUser);

            jsonObject.put("companyUser",companyUserService.isJoinedCompany(loginUser.getId()));

            jsonObject.put("token",token);
            return Result.success(jsonObject);
        }
        return Result.error("登陆失败");
    }
    /*
    * 2022.03.10
    * 王志羽
    * 用户注册
    * */
    @PostMapping("UserRegister")
    public Result register(@RequestBody Userinfo userinfo){

        String salt = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(userinfo.getPassword().getBytes()).substring(5,29).getBytes());
        userinfo.setSalt(salt);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("existUser",userinfoService.isExist(userinfo));

        userinfoService.save(userinfo);
        return Result.success(jsonObject);

    }
    /*
    * 2022.3.22
    * 王志羽
    * 初始化用户信息
    * */
    @GetMapping("/initEditData/{id}")
    public Result initEditData(@PathVariable Integer id){

        return Result.success(companyUserService.isJoinedCompany(id));
    }

    /*
    * 2022.3.23
    * 王志羽
    * 保存用户信息
    * */
    @PostMapping("/saveUserinfo")
    public Result saveUserinfo(Userinfo userinfo,MultipartFile file){
        System.out.println(123);
        System.out.println(userinfo);
        if(file != null && !file.isEmpty()){
            if(file.getSize()>1024*1024*2){
                return Result.error();
            }
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            if (!",jpg,jpeg,gif,webp,png,".contains(","+ext.toLowerCase()+",")){
                return Result.error();
            }
            try {
                String path = ResourceUtils.getURL("classpath:").getPath()+"/static/uploadFiles/headerPics";
                String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
                file.transferTo(new File(path,fileName));
                System.out.println(fileName);
                userinfo.setHeaderPic(fileName);
                System.out.println(userinfo.getHeaderPic());
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error();
            }

        }

        userinfo.setSalt(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(userinfo.getPassword().getBytes()).substring(5,29).getBytes()));

        userinfoService.updateUserinfoById(userinfo);
        System.out.println(userinfo);
        return Result.success("成功");
    }

@GetMapping("/showIndex")
    public Result showIndex(HttpServletRequest request){
    JSONObject jsonObject = new JSONObject();
    CompanyUser companyUser = (CompanyUser)request.getAttribute("companyUser");
    if(companyUser!=null){
        Department department = new Department();
        Company company = new Company();
        Position position = new Position();
        Userinfo userinfo = new Userinfo();
        department = departmentService.getById(companyUser.getDepartmentId());
        company = companyService.getById(companyUser.getCompanyId());
        System.out.println(company);
        position = positionService.getById(companyUser.getPositionId());
        userinfo = userinfoService.getById(companyUser.getUserinfoId());
        companyUser.setCompany(company).setDepartment(department).setPosition(position).setUserinfo(userinfo);
        jsonObject.put("companyUser",companyUser);
    }
    jsonObject.put("userinfo",request.getAttribute("userinfo"));
    return  Result.success("showIndex",jsonObject);
}
@GetMapping("/minister/logout")
    public Result mininsterLogout(HttpServletRequest request){
        CompanyUser companyUser = (CompanyUser)request.getAttribute("companyUser");
        Userinfo userinfo = (Userinfo) request.getAttribute("userinfo");
        return  Result.success("logout");
}


}
